/**
 * Copyright (c) 2016-2019 ykf All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.basic.modules.oss.cloud;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.basic.common.exception.RRException;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;

/**
 * 阿里云存储
 *
 * @author Mark sunlightcs@gmail.com
 */
public class AliyunCloudStorageService extends CloudStorageService {
    private OSSClient client;

    public AliyunCloudStorageService(CloudStorageConfig config) {
        this.config = config;

        //初始化
        init();
    }

    private void init() {
        client = new OSSClient(config.getAliyunEndPoint(), config.getAliyunAccessKeyId(),
                config.getAliyunAccessKeySecret());
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        try {
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType("text/plain;charset=utf-8");

            client.putObject(config.getAliyunBucketName(), path, inputStream, metadata);
        } catch (Exception e) {
            throw new RRException("上传文件失败，请检查配置信息", e);
        }

        return config.getAliyunDomain() + "/" + path;
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix, String mklx) {
        return upload(data, getPath(config.getAliyunPrefix(), suffix, mklx));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getAliyunPrefix(), suffix, ""));
    }

    @Override
    public void deleteFile(String path) {
        try {
            String objectName = path.replace(config.getAliyunDomain() + "/", "");
            client.deleteObject(config.getAliyunBucketName(), objectName);
        } catch (Exception e) {
            throw new RRException("删除文件失败: " + path, e);
        }
    }

    @Override
    public URL getDownLoadUrl(GeneratePresignedUrlRequest request) {
        return client.generatePresignedUrl(request);
    }
}